package felix.things.router.modbus.net;

import com.ghgande.j2mod.modbus.io.AbstractModbusTransport;
import com.ghgande.j2mod.modbus.io.ModbusTCPTransport;
import felix.things.router.modbus.transport.TcpTransportConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Felix
 * @date 2019/10/30
 **/
@Component
@Slf4j
public class TcpModbusMasterFactory {

    public static AbstractModbusTransport createModbusTransport(TcpTransportConfiguration transportConfiguration) {
        /*
         * Create a ModbusTCPListener with the default interface value. The
         * second optional value is the TCP port number and the third
         * optional value is the Modbus unit number.
         */
        try {
            Socket socket = new Socket(transportConfiguration.getHost(), transportConfiguration.getPort());
            log.debug("connecting to 【{}】", socket.toString());
            return new ModbusTCPTransport(socket);
        } catch (ConnectException c) {
            log.error("connection lost 【{}】", transportConfiguration.getHost() + ":" + transportConfiguration.getPort());
            return null;
        } catch (UnknownHostException x) {
            log.error("unknown host 【{}】", transportConfiguration.getHost(), x);
            return null;
        } catch (IOException e) {
            log.error("unknown exception 【{}】", transportConfiguration, e);
            return null;
        }
    }
}
